<template>
    <div
        v-if="showTable"
        class="tableContainer"
        :style="{ height: computedHeight }"
    >
        <div class="tableWrap">
            <el-table
                element-loading-text=" "
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.1)"
                :data="tableData"
                :height="
                    paginationShow
                        ? this.autoHeightCom - 50
                        : this.autoHeightCom
                "
                :header-cell-style="tableHeaderColor"
                :row-class-name="tableRowClassName"
                :cell-style="cellStyle"
                :row-key="rowKey"
                @selection-change="handleSelectionChange"
                ref="table"
                :empty-text="emptyTextReal"
                :highlight-current-row="radioSelect"
                @current-change="radioHandleCurrentChange"
                @row-click="rowClick"
                @row-dblclick="rowDblclick"
                :tree-props="treeProps"
                :summary-method="summaryMethod"
                :show-summary="showSummary"
                :border="true"
            >
                <el-table-column
                    align="center"
                    v-if="showSelection"
                    type="selection"
                    :reserve-selection="true"
                    width="55"
                ></el-table-column>

                <el-table-column
                    v-if="showIndex"
                    label="序号"
                    type="index"
                    width="70"
                    align="center"
                ></el-table-column>
                <!-- :formatter="formatterFn" -->
                <el-table-column
                    v-for="(item, indexKeySet) in keySetCopy"
                    :key="item.label"
                    :label="item.label"
                    :prop="item.englishName"
                    :width="
                        formatWidth(item)
                    "
                    :min-width="item.minWidth ? item.minWidth : 100"
                    :show-overflow-tooltip="
                        item.showOverflowTooltip === false ? false : true
                    "
                    :align="item.align ? item.align : 'left'"
                    showIndex
                    :sortable="item.sortable ? item.sortable : false"
                    :sort-method="
                        item.sortFn
                            ? item.sortFn
                            : (a, b) => defaultSort(a, b, item.englishName)
                    "
                >

                    <template #header="scope" >
                        <vxe-pulldown ref="xDown1" transfer  >
                            <template #default>
                                <div
                                    @click="showPullDown(indexKeySet)"
                                    style="cursor: pointer"
                                >
                                    {{ scope.column.label }}
                                </div>
                            </template>
                            <template #dropdown>
                                <el-card>
                                    <el-checkbox-group
                                        v-model="checkboxGroup1"
                                        size="small"
                                        class="checkboxGroupWrap"
                                        :min="1"
                                    >
                                        <el-checkbox
                                            :label="k.label"
                                            border
                                            v-for="k in keySet"
                                            :key="k.englishName"
                                        ></el-checkbox>
                                    </el-checkbox-group>
                                    <div style="margin-top: 10px">
                                        <el-button
                                            size="small"
                                            type="primary"
                                            @click="confirm(indexKeySet)"
                                        >
                                            确定
                                        </el-button>
                                        <el-button
                                            size="small"
                                            @click="reset(indexKeySet)"
                                        >
                                            还原
                                        </el-button>
                                    </div>
                                </el-card>
                            </template>
                        </vxe-pulldown>

                        <!-- {{ scope.column.label }} -->
                    </template>
                    <!-- <template #header="scope" v-else>
                         {{ scope.column.label }}
                    </template> -->
                    <template #default="{ row, $index }">
                        <span v-if="item.isSlot" class="names">
                            <slot
                                :name="item.slotName"
                                :row="row"
                                :index="$index"
                            ></slot>
                        </span>
                        <span v-else class="names">
                            {{
                                item.formatter
                                    ? item.formatter(row[item.englishName])
                                    : row[item.englishName]
                            }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    :width="handlerShowWidth"
                    v-if="handlerShow"
                    :fixed="isIe ? false : 'right'"
                >
                    <template #default="{ row, $index }">
                        <slot name="handler" :row="row" :index_="$index"></slot>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="paginationShow">
            <el-pagination
                style="float: right; margin-top: 10px; height: 38px"
                :currentPage="pageNumber"
                :page-size="pageSize"
                :page-sizes="pageSizes"
                :background="true"
                layout="total,  prev, pager, next,sizes, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
</template>

<script>
import isIEBrowser from '@/utils/isIe'
export default {
    name: 'tableList',
    props: {
        keySet: {
            type: Array,
            default: () => [],
        },
        tableData: {
            type: Array,
            default: () => [],
        },
        treeProps: {
            type: Object,
            default: () => {
                children: 'children'
            },
        },
        showSelectColumn: {
            type: Boolean,
            default: false,
        },
        loading: {
            type: Boolean,
            default: false,
        },
        showSummary: {
            type: Boolean,
            default: false,
        },
        summaryMethod: {
            type: Function,
            default: null,
        },
        handlerShow: {
            type: Boolean,
            default: false,
        },
        handlerShowWidth: {
            type: String,
            default: '150',
        },
        handlerFixed: {
            type: [String, Boolean],
            default: false,
        },
        emptyText: {
            type: String,
            default: '',
        },
        showIndex: {
            type: Boolean,
            default: false,
        },
        paginationShow: {
            type: Boolean,
            default: false,
        },
        showSelection: {
            type: Boolean,
            default: false,
        },
        radioSelect: {
            type: Boolean,
            default: true,
        },
        height: {
            type: String,
            default: '100%',
        },
        heightMin: {
            default: 0,
        },
        maxHeight: {
            default: '0',
        },
        total: {
            type: Number,
            default: 0,
        },
        pageNumber: {
            type: Number,
            default: 1,
        },
        pageSize: {
            type: Number,
            default: 5,
        },
        pageSizes: {
            type: Array,
            default: ()=>[5, 10, 15, 20],
        },
        rowKey: {
            type: String,
            default: 'id',
        },
    },
    data() {
        return {

            keySetCopy: [],
            emptyTextReal: ' ',
            autoHeightCom: '0',
            checkboxGroup1: [],
            showTable: true,
            isIe: isIEBrowser(),
        }
    },
    mounted() {
        this.getAutoHeight()
    },
    methods: {
        formatWidth(item){
            let width;
            if(item.width === 'labelWidth'){
                if(item.label){
                    width = item.label.length * 14 + 14 + ''
                }
                if(item.label&& item.sortable){
                    width = item.label.length * 14 + 14 + 34 + ''
                }
            }else if(item.width){
                width =  item.width;
            }else{
                width =  undefined;
            }
            return width;
        },
        resetTable() {
            this.showTable = false
            this.$nextTick(() => {
                this.showTable = true
            })
        },
        confirm(i) {
            this.keySetCopy = this.checkboxGroup1.map((item) => {
                return this.keySet.find((k) => k.label === item)
            })
            this.resetTable()
            // this.$emit("pullDown",[])
        },
        cancel(i) {
            if (this.$refs.xDown1) {
                this.$refs.xDown1[i].hidePanel()
            }
            this.resetTable()
        },
        reset(i) {
            this.resetTable()
            this.keySetCopy = this.keySet
            this.checkboxGroup1 = this.keySet.map((item) => item.label)
        },
        showPullDown(i) {
            if(this.showSelectColumn){
                this.$refs.xDown1[i].showPanel()
            }
        },
        // formatterFn(row, column, cellValue, index) {
        //   // console.log(row)
        //   // console.log(column)
        //   // console.log(cellValue)
        //   // console.log(index)
        //     return row.address;
        // },
        defaultSort(a, b, t) {
            if (a[t] < b[t]) {
                return -1 // s
            }
            if (a[t] > b[t]) {
                return 1
            }
            return 0
        },
        // 自适应表格列宽
        flexColumnWidth(str, arr1, label, flag = 'max') {
            // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
            // flag为可选值，可不传该参数,传参时可选'max'或'equal',默认为'max'
            // flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度。
            str = str + ''
            let columnContent = ''
            if (
                !arr1 ||
                !arr1.length ||
                arr1.length === 0 ||
                arr1 === undefined
            ) {
                return
            }
            if (!str || !str.length || str.length === 0 || str === undefined) {
                return
            }
            if (flag === 'equal') {
                // 获取该列中第一个不为空的数据(内容)
                for (let i = 0; i < arr1.length; i++) {
                    if (arr1[i][str].length > 0) {
                        columnContent = arr1[i][str]
                        break
                    }
                }
            } else {
                // 获取该列中最长的数据(内容)
                let index = 0
                for (let i = 0; i < arr1.length; i++) {
                    if (arr1[i][str] === null) {
                        return
                    }
                    const now_temp = arr1[i][str] + ''
                    const max_temp = arr1[index][str] + ''
                    if (now_temp.length > max_temp.length) {
                        index = i
                    }
                }

                columnContent = arr1[index][str]
                if (columnContent.length < label.length) {
                    columnContent = label
                }
            }
            // 以下分配的单位长度可根据实际需求进行调整
            let flexWidth = 0
            for (const char of columnContent) {
                if (
                    (char >= 'A' && char <= 'Z') ||
                    (char >= 'a' && char <= 'z')
                ) {
                    // 如果是英文字符，为字符分配8个单位宽度
                    flexWidth += 8
                } else if (char >= '\u4e00' && char <= '\u9fa5') {
                    // 如果是中文字符，为字符分配15个单位宽度
                    flexWidth += 14
                } else {
                    // 其他种类字符，为字符分配8个单位宽度
                    flexWidth += 9
                }
            }
            if (flexWidth < 60) {
                // 设置最小宽度
                flexWidth = 60
            }
            // if (flexWidth > 250) {
            //   // 设置最大宽度
            //   flexWidth = 250
            // }
            if (columnContent.length == label.length) {
                return flexWidth + 10 + 'px'
            } else {
                return flexWidth + 6 + 'px'
            }
        },
        getAutoHeight() {
            let el = document.querySelector('#app'),
                elParent = el.parentNode,
                pt = this.getStyle(elParent, 'paddingTop'),
                pb = this.getStyle(elParent, 'paddingBottom')
            this.$nextTick(() => {
                // 60是顶层 - 27是面包屑 +10 是在ie下进行兼容底部滚动条10先像素
                if (this.maxHeight == '0') {
                    this.autoHeightCom =
                        elParent.clientHeight -
                        (pt + pb) -
                        this.heightMin -
                        66 -
                        27 +
                        10
                } else {
                    this.autoHeightCom = this.maxHeight - 66 - 27 + 10
                }
                if (this.autoHeightCom < 100) {
                    this.autoHeightCom = 100
                }
            })
        },
        getStyle(obj, attr) {
            let result = obj.currentStyle
                ? obj.currentStyle[attr].replace('px', '')
                : document.defaultView
                      .getComputedStyle(obj, null)
                      [attr].replace('px', '')
            return Number(result)
        },

        handleCurrentChange(val) {
            this.$emit('handleCurrentChange', val)
        },
            tableRowClassName({ row, rowIndex }) {
      row.selfIndex = rowIndex;
 },
        radioHandleCurrentChange(val) {
            this.$emit('radioHandleCurrentChange', val)
        },
        rowClick(val,a,b) {
            this.$emit('rowClick', val)
        },
        rowDblclick(val) {
            this.$emit('rowDblclick', val)
        },
        handleSelectionChange(val) {
            this.$emit('handleSelectionChange', {
                ids: val,
                cb: () => {},
            })
        },
        selectableIsDisabled(row) {
            // 多选设置为禁用
            let res = false
            this.$emit('selectableIsDisabled', {
                row: row,
                cb: (fVal = false) => {
                    res = !fVal
                },
            })
            return res
        },
        handleSizeChange(val) {
            this.$emit('handleSizeChange', val)
        },
        tableHeaderColor({ row, column, rowIndex, columnIndex }) {
            let res = { background: '#F5F8FB', color: '#383B40' }
            return res
        },

        cellStyle({ row, column, rowIndex, columnIndex }) {
            let res = {}
            return res
        },

        clear() {
            this.$refs.table.clearSelection()
        },
        setSelectRow(val) {
            // debugger
            // 这一直有问题, 选中第二行,清空后选中第一行
            setTimeout(()=>{
                if(val){
                this.$refs.table.setCurrentRow(val)
            }else{
                this.$refs.table.setCurrentRow()
            }
            })
        },
    },
    computed: {
        computedHeight() {
            return this.autoHeightCom + 'px'
        },
    },
    watch: {
        keySet: {
            handler(newVal, oldVal) {
                if (newVal && newVal.length) {
                    this.keySetCopy = this.keySet
                    this.checkboxGroup1 = this.keySet.map((item) => item.label)
                }
            },
            immediate: true,
        },
        tableData(newVal, oldVal) {
            if (this.emptyText) {
                this.emptyTextReal = this.emptyText
            } else {
                this.emptyTextReal = '未查询到符合条件数据!'
            }
        },
    },
}
</script>
<style scoped lang="scss">
.tableContainer {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    // overflow: hidden;
    // overflow: hidden auto;
    overflow-y: auto;
    overflow-x: hidden;
    overflow: auto;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .tableWrap {
        .el-table {
            width: 100%;
            // width: 100vw;
        }
    }
}
.names {
    color: #383b40;
    font-weight: 400;
}

.checkboxGroupWrap {
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;
    ::v-deep .el-checkbox {
        display: block;
        margin-right: 0;
        margin-bottom: 6px;
    }
    ::v-deep .el-checkbox.is-bordered + .el-checkbox.is-bordered {
        margin-left: 0;
    }
}
// ::v-deep .vxe-pulldown .vxe-pulldown--panel{
//   z-index: 9999 !important;
// }
</style>
<style lang="scss">
.vxe-pulldown--panel.is--transfer {
    z-index: 8888888 !important;
}
.tableContainer {
    --el-pagination-border-radius: 2px;
    .el-pagination.is-background .btn-next,
    .el-pagination.is-background .btn-prev,
    .el-pagination.is-background .el-pager li {
        background: none;
        border: 1px solid var(--el-border-color-base);
        border-radius: var(--el-pagination-border-radius);
    }

    .el-table__fixed::before {
        background-color: transparent;
    }
}
.el-table__body {
    margin-bottom: 10px;
}
.el-table__body tr.current-row > td.el-table__cell {
    background-color: #fbec88 !important;
}

.el-table .el-table__cell {
    padding: 4px 0;
}
</style>
